<?php
class common{
	/*
	 * Author  : Cùi Bắp
	 * Created : 20-10-2011
	 */
	
	static function ckEditor($id = "editor1",$value=""){	 
	 echo '
	 <script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
	 <textarea class="ckeditor" cols="80" id="'.$id.'" name="'.$id.'" rows="10">
	 '.$value.'
	 </textarea>
	 ';
	}
	static function getParamsForService($numCol,$arrColName,$arrData)
	{
		$string = $numCol;
		foreach($arrColName as $row){
			$string .= "~".$row;
		}
		foreach($arrData as $row){
			$string .= "~".$row;
		}
		return $string;
	}
	/*
	 * Convert current Date to System Date
	 */
	static function convertToSystemDate($date)
	{
		return implode("-",array_reverse(explode("/",$date)));
	}
	
	static function convertToCultureDate($date)
	{
		return implode("/",array_reverse(explode("-",$date)));
	}
		
	static function addDate($number,$date,$format)
	{
		list($nam,$thang,$ngay) = explode("-",$date);
		$k = "+".$number." day";
		return date($format,strtotime($k,mktime(0,0,0,$thang,$ngay,$nam)));
	}
	
	static function subDate($number,$date,$format)
	{
		list($nam,$thang,$ngay) = explode("-",$date);
		$k = "-".$number." day";
		return date($format,strtotime($k,mktime(0,0,0,$thang,$ngay,$nam)));
	}
    static function pagingAuto($count,$position='right',$formName = 'frmPaging',$loadInto = 'main_content') 
    {
        if($count >0){
        if(isset($_POST['paging'])){
            $arrPaging = $_POST['paging'];
            //var_dump($arrPaging);exit;
            $currentPageNumber = $arrPaging[0];
            $limit = $arrPaging[1];
            if($limit == ''){
            $limit = $count;
            }
            $offset = $arrPaging[2];
        }else{
            $currentPageNumber = 1;
            $limit = config::getPage('limit');
            $offset = 0;
        }
        $totalPageNumber = ceil($count/$limit); 
        $next = $currentPageNumber+1;
        $last = $totalPageNumber-1;
        $pre = $currentPageNumber-1;
		
		$start = $pre * $limit + 1;
		if($currentPageNumber == $totalPageNumber){
			$end = $count;
		} else {
			$end = $currentPageNumber * $limit;
		}
        $html = '<form name="'.$formName.'Form" action="">
			<table border="0" cellpadding="0" cellspacing="0" id="paging-table" style="text-align:left;float:'.$position.'">
			<tr>
			<td style="text-align: left">Showing '.$start.'-'.$end.' of '.$count.' results </td>
			<td style="width: 210px">';
		$html .= '<a onclick="';
        if($currentPageNumber != 1) {
			$html .=  "common.firstPage('".$formName."Form','".$loadInto."')";
        }
        $html .='" class="page-far-left"></a>';
		$html .='<a onclick="';
        if($currentPageNumber != 1) {
			$html .=  "common.previousPage(".$pre.",".$offset.",'".$formName."Form','".$loadInto."')";
        }
        $html .='" class="page-left"></a><div id="page-info">Page <strong>'.$currentPageNumber.'</strong> / ';
        $html .= $totalPageNumber.'</div>';
		$html .= '<a onclick="';
        if($currentPageNumber != $totalPageNumber) {
			$html .=  "common.nextPage(".$next.",".$offset.",'".$formName."Form','".$loadInto."')";
        }
        $html .= '" class="page-right"></a><a onclick="';
		if($currentPageNumber != $totalPageNumber) {
			$html .=  "common.lastPage(".$last.",".$totalPageNumber.",'".$formName."Form','".$loadInto."')";
        }
        $html .= '" class="page-far-right"></a></td><td width="140px"> ';
        $html .='<select name="limit" class="" onchange="'."common.changePageLimit('".$formName."Form','".$loadInto."')".'" >';
        $arrLimit = array(
			'5' => '',
			'10' => '',
			'20' => '',
			'50' => '',
			'100' => ''
        );
        $arrLimit[$limit] = 'selected=""';
		$html .= '<option value="5" '.$arrLimit['5'].'>Hiển thị 5 kết quả</option>';
		$html .= '<option value="10" '.$arrLimit['10'].'>Hiển thị 10 kết quả</option>';
		$html .= '<option value="20" '.$arrLimit['20'].'>Hiển thị 20 kết quả</option>';
		$html .= '<option value="50" '.$arrLimit['50'].'>Hiển thị 50 kết quả</option>';
		$html .= '<option value="100" '.$arrLimit['100'].'>Hiển thị 100 kết quả</option>	</select></td></tr></table></form>';

        echo $html;
        $arr = array($limit,$offset,$html);
        return $arr;
        }else{
            $html = '<table cellspacing="0" cellpadding="0" border="0" width="330px" style="float: right;" id="paging-table">
			<tbody><tr>
			<td><a class="page-far-left" onclick=""></a><a class="page-left" onclick=""></a><div id="page-info">Page <strong>1</strong> / 1</div><a class="page-right" onclick=""></a><a class="page-far-right" onclick=""></a></td><td> <select class="" name="limit"><option selected="" value="10">Hiển thị 10 kết quả</option><option value="20">Hiển thị 20 kết quả</option><option value="50">Hiển thị 50 kết quả</option><option value="100">Hiển thị 100 kết quả</option>	</select></td></tr></tbody></table>';
            echo $html;
            $arr = array(0,0,$html);
            return $arr;
        }
    }
    static function paging($count,$position='right',$formName = 'frmPaging',$loadInto = 'main_content'){    if($count >0){
            if(isset($_POST['paging'])){
                $arrPaging = $_POST['paging'];
                //var_dump($arrPaging);exit;
                $currentPageNumber = $arrPaging[0];
                $limit = $arrPaging[1];
                if($limit == ''){
                $limit = $count;
                }
                $offset = $arrPaging[2];
            }else{
                $currentPageNumber = 1;
                $limit = config::getPage('limit');
                $offset = 0;
            }
            $totalPageNumber = ceil($count/$limit); 
            $next = $currentPageNumber+1;
            $last = $totalPageNumber-1;
            $pre = $currentPageNumber-1;
            $html = '<form name="'.$formName.'Form" action="">
                <table border="0" cellpadding="0" cellspacing="0" id="paging-table" width="330px" style="float:'.$position.'">
                <tr>
                <td>';
            $html .= '<a onclick="';
            if($currentPageNumber != 1) {
                $html .=  "common.firstPage('".$formName."Form','".$loadInto."')";
            }
            $html .='" class="page-far-left"></a>';
            $html .='<a onclick="';
            if($currentPageNumber != 1) {
                $html .=  "common.previousPage(".$pre.",".$offset.",'".$formName."Form','".$loadInto."')";
            }
            $html .='" class="page-left"></a><div id="page-info">Page <strong>'.$currentPageNumber.'</strong> / ';
            $html .= $totalPageNumber.'</div>';
            $html .= '<a onclick="';
            if($currentPageNumber != $totalPageNumber) {
            $html .=  "common.nextPage(".$next.",".$offset.",'".$formName."Form','".$loadInto."')";
            }
            $html .= '" class="page-right"></a><a onclick="';
            if($currentPageNumber != $totalPageNumber) {
            $html .=  "common.lastPage(".$last.",".$totalPageNumber.",'".$formName."Form','".$loadInto."')";
            }
            $html .= '" class="page-far-right"></a></td><td> ';
            $arrLimit = array(
            '10' => '',
            '20' => '',
            '50' => '',
            '100' => ''
            );
            $arrLimit[$limit] = 'selected=""';        
            $html .='<select name="limit" class="" onchange="'."common.changePageLimit('".$formName."Form','".$loadInto."')".'" >';
            $html .= '<option value="10" '.$arrLimit['10'].'>Hiển thị 10 kết quả</option>';
            $html .= '<option value="20" '.$arrLimit['20'].'>Hiển thị 20 kết quả</option>';
            $html .= '<option value="50" '.$arrLimit['50'].'>Hiển thị 50 kết quả</option>';
            $html .= '<option value="100" '.$arrLimit['100'].'>Hiển thị 100 kết quả</option>	</select></td></tr></table></form>';
            $arr = array($limit,$offset,$html);
            return $arr;
        }else{
            $html = '<table cellspacing="0" cellpadding="0" border="0" width="330px" style="float: right;" id="paging-table">
			<tbody><tr>
			<td><a class="page-far-left" onclick=""></a><a class="page-left" onclick=""></a><div id="page-info">Page <strong>1</strong> / 1</div><a class="page-right" onclick=""></a><a class="page-far-right" onclick=""></a></td><td> <select class="" name="limit"><option selected="" value="10">Hiển thị 10 kết quả</option><option value="20">Hiển thị 20 kết quả</option><option value="50">Hiển thị 50 kết quả</option><option value="100">Hiển thị 100 kết quả</option>	</select></td></tr></tbody></table>';
            echo $html;
            $arr = array(0,0,$html);
            return $arr;
        }
    }
    /*
     * @name = delete,add,back,save,help
    */
    static function showButton($name){     
       $html  = "<script>\n";
       $html .= "common.showButton('".$name."');\n";
       $html .= "</script>\n";      
       echo $html; 
    }
    
    static function datePicker($id =""){   
        $html  = "<script>\n";
        $html .= "$(function() {\n";
        $html .= "$( '#".$id."' ).datepicker(\n";
        $html .= "{dateFormat: 'dd/mm/yy'}\n";
        $html .= ");\n";		
        $html .= "});\n";
        $html .= '</script>';
        echo $html;
    }

    static function MysqlDateToVnDate($mysqldate){
        if($mysqldate!=""){
        $d = explode(" ",$mysqldate);
        $d = explode("-",$d[0]);
        return (int)$d[2]."/".(int)$d[1]."/".(int)$d[0];
        }
    }
    static function getYear(){
            $year = new Zend_Session_Namespace('year');
            if(!isset($year->year)){
                    $d=getdate();
                    $year->year = $d['year'];
            }
            return $year->year;
    }
    static function AutoComplete($data, $fieldid, $fieldname, $controlid, $controltext, $fullcompare, $style, $onokaction, $defaultid, $defaultname, $iscombobox=false) {
        if ($iscombobox) {
            $html = "
           <select name=$controlid id=$controlid style='$style'>
                        <option value=''>-- Chọn --</option>
           ";
            foreach ($data as $item) {
                $html .= "<option value='" . $item[$fieldid] . "' " . ($item[$fieldid] == $defaultid ? "selected=selected" : "") . ">" . htmlspecialchars($item[$fieldname]) . "</option>";
            }
            $html .="
           </select>
           ";
        } else {
            $html = "
             <script>
              var DATA_$controlid = new Array();
            ";
            foreach ($data as $item) {
                if ($item[$fieldid] == $defaultid
                )
                    $defaultname = $item[$fieldname];
                $html.="DATA_" . $controlid . "[DATA_" . $controlid . ".length]=new Array('" . $item[$fieldid] . "','" . str_replace("'", "\\'", $item[$fieldname]) . "');";
            }
            $html.="
             </script>
            ";
            $html.="
             <input autocomplete=off onclick='cancelEvent(event)' class=autocombobox value='$defaultname' type=text style='$style' name=$controltext id=$controltext  onkeydown='at_KeyDown(event)' onkeyup='at_Display(event)' onfocus=\"at_Load('$controltext','$controlid',DATA_$controlid," . ($fullcompare == true ? "true" : "false") . ",'$onokaction');\">
             <input type=hidden style='$style' name=$controlid id=$controlid value='$defaultid'>
            ";
        }
        return $html;
    }

	//random a string of numbers with $len.Only fill number
	static function RandomNumber($len)
	{
		$n = '';
		for($i=0;$i<$len;$i++){
			$n.=rand(0,9);
		}
		return $n;
	}
	
	//random a string from STR const.Only fill number
	static function RandomLetter($len)
	{
		define(STR, 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
		$n = '';
		for($i=0;$i<$len;$i++){
			$n.=substr(STR, rand(0,(strlen(STR)-1)), 1);
		}
		return $n;
	}
    
	//general password random
	static function RandomPassword()
	{
		return substr(md5(uniqid(rand(),1)),3,10);	
	}
    
	/**
    * Get Current request info
    */
	static function getRequestInfo()
	{
        $module     = Zend_Controller_Front::getInstance()->getRequest()->getModuleName();
        $controller = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
        $action     = Zend_Controller_Front::getInstance()->getRequest()->getActionName();
        $arr = array(
            "module"=> $module,
            "controller"=> $controller,
            "action"=> $action
        );
        return $arr;
	}
	static function formatPath($path,$seperator,$standardDelimiter = ':'){
        // colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)
        //$pattern = '/[:\|\\\\\/\s]/';
        $pattern = '/[\|\\\\\/]/';
        // replace delimiters with standard delimiter, also removing redundant delimiters
        $path = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $path);
        $result = explode($standardDelimiter, $path);
        $result[0] .= $standardDelimiter;
        $newPath = implode($seperator, $result);        
        return $newPath; 
	}
    
	static function pagination($iteratorURL, $itemAmount, $position ='right', $itemPerPage = 10, $currentPage = 1){
		if($itemAmount>0){
			
			
			
			$totalPage = ceil($itemAmount/$itemPerPage);
			$nextPage = $currentPage + 1;
			$previousPage = $currentPage -1;
			$lastFullPage = $totalPage;
			$offset = $previousPage * $itemPerPage;
			
			$start = $offset + 1;
			if($currentPage == $totalPage){
				$end = $itemAmount;
			} else {
				$end = $currentPage * $itemPerPage;
			}
			
			$html = '<form name="pagination-frm" action="">
					<table border="0" cellpadding="0" cellspacing="0" id="paging-table" style="text-align:left;float:'.$position.'">
					<tr>
					<td style="text-align: left">Showing '.$start.'-'.$end.' of '.$itemAmount.' results </td>
					<td style="width: 250px">';
			
			
			if($previousPage > 0) {
				$html .= '<a href="';
				$html .=  $iteratorURL.'/limit/'.$itemPerPage.'/page/1';
				$html .='" class="page-far-left-active"></a>';
			} else {
				$html .= '<a href="#';
				$html .='" class="page-far-left"></a>';
			}
			
			if($previousPage > 0) {
				$html .='<a href="';
				$html .= $iteratorURL.'/limit/'.$itemPerPage.'/page/'.$previousPage;
				$html .= '" class="page-left-active"></a>';
			} else {
				$html .='<a href="#';
				$html .= '" class="page-left"></a>';
			}
			$html .= '<div id="page-info">Page ';
			
			$html .= '<select name="PAGENUMBER" id="PAGENUMBER" class="" >';
			for($i=1;$i<=$totalPage;$i++){
				if($i==$currentPage){
					$html .= 	'<option value="'.$i.'" selected="selected">'.$i.'</option>';
				} else {
					$onclickFunction = "window.location = '".$iteratorURL."/page/".$i."'";
					$html .= 	'<option value="'.$i.'" onclick="'.$onclickFunction.'">'.$i.'</option>';
				}
			}
			$html .= '</select> of ';
			$html .= $totalPage.'</div>';
			if($currentPage < $totalPage) {
				$html .= '<a href="';
				$html .=  $iteratorURL.'/limit/'.$itemPerPage.'/page/'.$nextPage;
				$html .='" class="page-right-active"></a>';
			} else {
				$html .= '<a href="#';
				$html .='" class="page-right"></a>';
			}
			
			
			if($currentPage < $totalPage) {
				$html .= '<a href="';
				$html .=  $iteratorURL.'/limit/'.$itemPerPage.'/page/'.$totalPage;
				$html .='" class="page-far-right-active"></a>';
			} else {
				$html .= '<a href="#';
				$html .='" class="page-far-right"></a>';
			}
			$arrLimit = array(
				'5'	  => '',
				'10'  => '',
				'20'  => '',
				'50'  => '',
				'100' => ''
			);
			
			$arrLimit[$itemPerPage] = 'selected=""'; 
			$html .= '</td><td width="140px"> ';
			$html .= 'Item per page:';
			$html .= '<select name="limit" class="" >';
			$html .= '<option value="5" '.$arrLimit['5'].' onclick="window.location = '."'".$iteratorURL."/limit/5'".'">5</option>';
			$html .= '<option value="10" '.$arrLimit['10'].' onclick="window.location = '."'".$iteratorURL."/limit/10'".'">10</option>';
			$html .= '<option value="20" '.$arrLimit['20'].' onclick="window.location = '."'".$iteratorURL."/limit/20'".'">20</option>';
			$html .= '<option value="50" '.$arrLimit['50'].' onclick="window.location = '."'".$iteratorURL."/limit/50'".'">50</option>';
			$html .= '<option value="100" '.$arrLimit['100'].' onclick="window.location = '."'".$iteratorURL."/limit/100'".'">100</option>	';
			$html .= '</select></td></tr></table></form>';
			
			return $html;
		} else {
			return '';
		}
	}
}